﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;

namespace System.Windows
{
    /// <summary>
    /// Application Resources Utility.
    /// </summary>
    public static class ResourcesUtility
    {
        private static void UpdateColors(IEnumerable<KeyValuePair<object, object>> brushes)
        {
            foreach (var entry in brushes)
            {
                var resources = Application.Current.Resources;
                if (!resources.Contains(entry.Key))
                {
                    continue;
                }

                var current = resources[entry.Key] as SolidColorBrush;
                var next = entry.Value as SolidColorBrush;

                if (current != null && next != null && !current.Color.Equals(next.Color))
                {
                    current.Color = next.Color;
                }
            }
        }

        /// <summary>
        /// Overrides default Windows Phone brushes.
        /// </summary>
        /// <param name="resourceUri">Resource file <see cref="Uri">uri</see>.</param>
        /// <exception cref="InvalidOperationException"></exception>
        public static void OverrideDefaultBrushes(Uri resourceUri)
        {
            var dictionaries = new ResourceDictionary();

            try
            {
                var themeResourcesStyles = new ResourceDictionary {Source = resourceUri};

                dictionaries.MergedDictionaries.Add(themeResourcesStyles);
            }
            catch(Exception ex)
            {
                throw new InvalidOperationException(ex.Message, ex);
            }

            var brushes = dictionaries.MergedDictionaries[0].Where(e => e.Value is SolidColorBrush).ToList();

            UpdateColors(brushes);
        }
    }
}
